package ui;

import java.awt.Toolkit;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

/** Represents a DocumentFilter, which is instantiated by ui classes. 
 * The class contains default methods, which are necessary by the Class DocumentFilter api.
 * @author Matthias
 *
 */
public class LimitOfChar extends DocumentFilter {  
	  
    /**
     * int object used to define the maxlength of a textfield
     */
    private final int max;  
  
    /** Constructor of LimitoChar
     * @param maxLength		is an int, which defines the max number of digits the user can type in the
     * jtextfield. The constructor is instantiated and called by jtextfields in various ui classes, such as AdmCreate
     */
    public LimitOfChar(final int maxLength) {  
        max = maxLength;  
    }  
  
    /** (non-Javadoc)
     * @see javax.swing.text.DocumentFilter#insertString(javax.swing.text.DocumentFilter.FilterBypass, int, java.lang.String, javax.swing.text.AttributeSet)
     */
    @Override
	public void insertString(final DocumentFilter.FilterBypass fb, final int offset,  
            final String text, final AttributeSet attr) throws BadLocationException {  
        if (fb.getDocument().getLength() + text.length() <= max)  
               fb.insertString(offset, text, attr);  
          else Toolkit.getDefaultToolkit().beep();  
    }  

    /** (non-Javadoc)
     * @see javax.swing.text.DocumentFilter#replace(javax.swing.text.DocumentFilter.FilterBypass, int, int, java.lang.String, javax.swing.text.AttributeSet)
     */
    @Override
	public void replace(final DocumentFilter.FilterBypass fb, final int offset, final int length,  
            final String text, final AttributeSet attr) throws BadLocationException {  
        if (fb.getDocument().getLength() + text.length() - length <= max)  
               fb.replace(offset, length, text, attr);  
          else Toolkit.getDefaultToolkit().beep();  
    }
    
}  // end this class